<?php
/**
 * $Author: BEESSHOP $
 * ============================================================================
 * ============================================================================
 */
namespace app\controllers;

use app\models\CateRecorder;

class CateController extends BaseController{

    public function actionAdd(){
        $post = \Yii::$app->request->post();
        $id = intval($post['CateRecorder']['id']);
        if($id){
            $model = CateRecorder::find()->where('id=:id',[':id' => $id])->one();
            if(!$model){
                $result = ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
                return json_encode($result);
            }

            if($model->parent_id==0&&$post['CateRecorder']['parent_id']>0){
                $result = ['result'=>0,'data'=>'顶级栏目不能设置为下级'];
                return json_encode($result);
            }
        }else{
            $model = new CateRecorder();
            $model->addtime = time();
        }
        $result = $model->add($post);
        return json_encode($result);
    }


    public function actionList(){
        $list = CateRecorder::find()->where('parent_id=0')->asArray()->all();
        $arr = [];
        foreach($list as $k=>$v){
            $v['thumb_pic'] = \Yii::$app->params['base_url'].$v['thumb_pic'];
            array_push($arr,$v);
            $child = CateRecorder::find()->where('parent_id='.$v['id'])->asArray()->all();
            foreach($child as $c_k=>$c_v){
                $c_v['cate_name'] = "|---".$c_v['cate_name'];
                $c_v['thumb_pic'] = \Yii::$app->params['base_url'].$c_v['thumb_pic'];
                array_push($arr,$c_v);
            }
        }
        $result = ['result'=>1,'data'=>$arr];
        return json_encode($result);

    }


    public function actionParent(){
        $list = CateRecorder::find()->select(['id','cate_name'])->where('parent_id=0')->asArray()->all();
        $result = ['result'=>1,'data'=>$list];
        return json_encode($result);
    }


    public function actionOne(){
        $id = \Yii::$app->request->post('id');
        $model = CateRecorder::find()->where('id=:id',[':id' => $id])->asArray()->one();
        if(empty($model)){
            $result= ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
            return json_encode($result);
        }
        $model['thumb_pic'] = \Yii::$app->params['base_url'].$model['thumb_pic'];
        $result = ['result'=>1,'data'=>$model];
        return json_encode($result);
    }


    public function actionDel(){
        $id = \Yii::$app->request->post('id');
        $model = CateRecorder::find()->where('id=:id',[':id' => $id])->one();
        if(!$model){
            $result = ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
            return json_encode($result);
        }
        $model->delete();
        $result = ['result'=>1,'data'=>'操作成功'];
        return json_encode($result);
    }

}
